<template>
  <div class="student-management">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>学生信息管理</span>
          <el-button type="primary" @click="showAddForm">添加学生</el-button>
        </div>
      </template>
      
      <!-- 搜索框 -->
      <div class="search-box">
        <el-input v-model="searchName" placeholder="请输入学生姓名" style="width: 200px; margin-right: 10px;"></el-input>
        <el-button type="primary" @click="searchStudents">搜索</el-button>
        <el-button @click="loadStudents">重置</el-button>
      </div>
      
      <!-- 学生列表 -->
      <el-table :data="students" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column label="头像" width="80">
          <template #default="scope">
            <el-avatar :src="scope.row.avatarUrl || defaultAvatar" size="small"></el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="姓名" width="120"></el-table-column>
        <el-table-column prop="age" label="年龄" width="80"></el-table-column>
        <el-table-column prop="gender" label="性别" width="80"></el-table-column>
        <el-table-column prop="grade" label="年级" width="120"></el-table-column>
        <el-table-column prop="major" label="专业" width="150"></el-table-column>
        <el-table-column prop="phone" label="电话" width="150"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="200"></el-table-column>
        <el-table-column label="操作" width="250">
          <template #default="scope">
            <el-button size="small" @click="showEditForm(scope.row)">编辑</el-button>
            <el-button size="small" type="primary" @click="showAvatarUpload(scope.row)">头像</el-button>
            <el-button size="small" type="danger" @click="deleteStudent(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 添加/编辑学生对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px">
      <el-form :model="currentStudent" label-width="80px">
        <el-form-item label="姓名">
          <el-input v-model="currentStudent.name"></el-input>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input-number v-model="currentStudent.age" :min="1" :max="100"></el-input-number>
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="currentStudent.gender" placeholder="请选择性别">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年级">
          <el-select v-model="currentStudent.grade" placeholder="请选择年级">
            <el-option
              v-for="item in gradeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="专业">
          <el-input v-model="currentStudent.major"></el-input>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="currentStudent.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="currentStudent.email"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveStudent">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 头像上传对话框 -->
    <el-dialog title="上传头像" v-model="avatarDialogVisible" width="400px">
      <div class="avatar-upload">
        <el-upload
          class="avatar-uploader"
          action="/api/files/avatar/upload"
          :data="{ studentId: currentStudentId }"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <img v-if="currentAvatarUrl" :src="currentAvatarUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
        <div class="avatar-preview" v-if="currentAvatarUrl">
          <p>预览：</p>
          <el-avatar :src="currentAvatarUrl" :size="80"></el-avatar>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="avatarDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="avatarDialogVisible = false">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

// 学生列表
const students = ref([])
// 搜索姓名
const searchName = ref('')
// 加载状态
const loading = ref(false)
// 对话框显示状态
const dialogVisible = ref(false)
// 头像上传对话框显示状态
const avatarDialogVisible = ref(false)
// 对话框标题
const dialogTitle = ref('添加学生')
// 年级选项
const gradeOptions = ref([
  { label: '大一', value: '大一' },
  { label: '大二', value: '大二' },
  { label: '大三', value: '大三' },
  { label: '大四', value: '大四' },
])
// 当前编辑的学生
const currentStudent = ref({
  id: null,
  name: '',
  age: null,
  gender: '',
  grade: '',
  major: '',
  phone: '',
  email: '',
  avatarUrl: ''
})

// 当前学生ID（用于头像上传）
const currentStudentId = ref(null)
// 当前头像URL
const currentAvatarUrl = ref('')
// 默认头像
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'

// 页面加载时获取学生列表
onMounted(() => {
  loadStudents()
})

// 获取所有学生
const loadStudents = async () => {
  loading.value = true
  try {
    const response = await axios.get('/api/students')
    if (response.data.code === 200) {
      students.value = response.data.data
    }
  } catch (error) {
    ElMessage.error('获取学生列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索学生
const searchStudents = async () => {
  if (!searchName.value) {
    loadStudents()
    return
  }
  
  loading.value = true
  try {
    const response = await axios.get(`/api/students/search?name=${searchName.value}`)
    if (response.data.code === 200) {
      students.value = response.data.data
    }
  } catch (error) {
    ElMessage.error('搜索学生失败')
  } finally {
    loading.value = false
  }
}

// 显示添加表单
const showAddForm = () => {
  dialogTitle.value = '添加学生'
  currentStudent.value = {
    id: null,
    name: '',
    age: null,
    gender: '',
    grade: '',
    major: '',
    phone: '',
    email: '',
    avatarUrl: ''
  }
  dialogVisible.value = true
}

// 显示编辑表单
const showEditForm = (student) => {
  dialogTitle.value = '编辑学生'
  currentStudent.value = { ...student }
  dialogVisible.value = true
}

// 保存学生信息
const saveStudent = async () => {
  try {
    const response = await axios.post('/api/students', currentStudent.value)
    if (response.data.code === 200) {
      ElMessage.success('保存成功')
      dialogVisible.value = false
      loadStudents()
    } else {
      ElMessage.error('保存失败')
    }
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

// 删除学生
const deleteStudent = (id) => {
  ElMessageBox.confirm('确定要删除这个学生吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await axios.delete(`/api/students/${id}`)
      if (response.data.code === 200) {
        ElMessage.success('删除成功')
        loadStudents()
      } else {
        ElMessage.error('删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 显示头像上传对话框
const showAvatarUpload = (student) => {
  currentStudentId.value = student.id
  currentAvatarUrl.value = student.avatarUrl || ''
  avatarDialogVisible.value = true
}

// 头像上传成功处理
const handleAvatarSuccess = (response, file) => {
  if (response.code === 200) {
    ElMessage.success('头像上传成功')
    currentAvatarUrl.value = response.data
    // 更新学生列表中的头像
    const student = students.value.find(s => s.id === currentStudentId.value)
    if (student) {
      student.avatarUrl = response.data
    }
  } else {
    ElMessage.error('头像上传失败：' + response.message)
  }
}

// 头像上传前处理
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('头像图片只能是 JPG 或 PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('头像图片大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}
</script>

<style scoped>
.student-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-box {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.avatar-preview {
  margin-top: 20px;
  text-align: center;
}

.avatar-preview p {
  margin-bottom: 10px;
}
</style>